package com.spice.im.utils;

//import com.stb.appearancetime.R;


import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import cn.finalteam.galleryfinal.GalleryHelper;
import cn.finalteam.galleryfinal.GalleryImageLoader;
import cn.finalteam.galleryfinal.PhotoCropActivity;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.BitmapUtils;




//import cn.finalteam.toolsfinal.DateUtils;
import com.spice.im.utils.DateUtils;

import cn.finalteam.toolsfinal.DeviceUtils;
import cn.finalteam.toolsfinal.FileUtils;
import cn.finalteam.toolsfinal.Logger;














//import com.example.android.bitmapfun.util.AsyncTask;
import com.beem.push.utils.AsyncTask;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.spice.im.BaseDialog;
import com.spice.im.ContactFrameActivity;
import com.spice.im.R;
import com.spice.im.SpiceApplication;
import com.spice.im.attendance.AttendanceClassSection;
import com.spice.im.ui.HandyTextView;
import com.stb.isharemessage.service.XmppConnectionAdapter;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
//import cn.com.ctbri.pp2transitcard.tools.ConstValuesLib;
//import cn.com.ctbri.pp2transitcard.tools.R;

public class MyDialogPopWinProfile extends Dialog implements
		android.view.View.OnClickListener, ConstValuesLib,TextWatcher,
		OnCheckedChangeListener,OnDateChangedListener {
	public static final int ButtonCancle = 0;// 显示取消按钮
	public static final int ButtonConfirm = 1;// 显示确定按钮
	public static final int ButtonBoth = 2;// 显示全部按钮
	public static final int ButtonNone = 3;// 不显示任何的按钮
	View view = null;
	Button btn_confirm;
	Button btn_cancel;
	int buttonNums = 2;
	//TextView theView;
//	TextView tx_title;
	Activity activity;
	boolean visiable = true;
	MyDialogListener listener;
	CharSequence g_Msg = "";
	String title = "";
	String posiBtnMsg = "";
	String negaBtnMsg = "";
	ViewGroup container;
	// 提示信息
	private String msg = null;
//	private TextView theView;//原textview  ---占位符号 显示拍照时，该textview不显示gone
//	private TextView textViewDialog2;//占位符号 显示拍照时，该textview不显示gone
	
	
    /** TextView选择框 */
//    private TextView mSelectTv;
	private EditText mBaseInfoName;//reg_baseinfo_et_name
	private EditText mBaseInfoNote;//reg_baseinfo_et_usersign
	private RadioGroup mRgGender;//reg_baseinfo_rg_gender
	private RadioButton mRbMale;//reg_baseinfo_rb_male
	private RadioButton mRbFemale;//reg_baseinfo_rb_female
	private HandyTextView mHtvConstellation;
	private HandyTextView mHtvAge;
	private DatePicker mDpBirthday;//reg_birthday_dp_birthday
	private boolean mIsChange = true;
	private boolean mIsGenderAlert;
	private BaseDialog mBaseDialog;
	
    String name = null;
    String gender = null;//默认0未知，1男，2女
    String usersign = null;
    String birthdayfull = null;
    String birthyear = null;
    String birthmonth = null;
    String birthday = null;
    
    public String getName(){
    	return name;
    }
    public String getGender(){
    	return gender;
    }
    public String getUsersign(){
    	return usersign;
    }
    public String getBirthdayfull(){
    	return birthdayfull;
    }
    public String getBirthyear(){
    	return birthyear;
    }
    public String getBirthmonth(){
    	return birthmonth;
    }
    public String getBirthday(){
    	return birthday;
    }
    
    
    
	private Calendar mCalendar;
	private Date mMinDate;
	private Date mMaxDate;
	private Date mSelectDate;
	private static final int MAX_AGE = 100;
	private static final int MIN_AGE = 12;
    

	private final OkListener mOkListener = new OkListener();
	private String CurrentUid;
	private String OtherUid;
	

    
    /**
     * Listener.
     */
    private class OkListener implements View.OnClickListener {
	
		/**
		 * Constructor.
		 */
		public OkListener() { }
	
		@Override
		public void onClick(View v) {
//			switch (v.getId()) {
//				case R.id.reg_photo_layout_selectphoto:
//					GalleryHelper.openGallerySingle(activity, true, new GalleryImageLoader());
//					break;
//	
//				case R.id.reg_photo_layout_takepicture:
//					takePhotoAction();
//				break;
//			}
	
		}
    };
	
//    public String getBaseInfoName(){
//    	return mBaseInfoName.getText().toString();
//    }
    
    

    
    
	private View lineSeperator;

	MyDialogContentClickListener contentListener;

	public MyDialogPopWinProfile(Activity activity) {
		super(activity);
		this.activity = activity;
	}

	public MyDialogPopWinProfile(Activity activity, int theme, MyDialogListener listener,
			int btnNums, String CurrentUid,String OtherUid,String CurrentName,
	       String CurrentNote,
	       String CurrentSex,
	       String CurrentBirthyear,
	       String CurrentBirthmonth,
	       String CurrentBirthday) {
		super(activity, theme);
		this.activity = activity;
		this.listener = listener;
		buttonNums = btnNums;
//		this.aClassSections = aClassSections;
		this.CurrentUid = CurrentUid;
		this.OtherUid = OtherUid;
		this.name = CurrentName;
		this.usersign = CurrentNote;
		this.gender = CurrentSex;
		this.birthyear = CurrentBirthyear;
		this.birthmonth = CurrentBirthmonth;
		this.birthday = CurrentBirthday;
	}

	public MyDialogPopWinProfile(Activity activity, int theme, MyDialogListener listener,
			int btnNums, String msg) {
		super(activity, theme);
		this.activity = activity;
		this.listener = listener;
		buttonNums = btnNums;
		this.msg = msg;
		this.g_Msg = msg;
	}

	public void setContentListener(MyDialogContentClickListener contentListener) {
		this.contentListener = contentListener;
	}

	public void setTitleTxt(String msg) {
		title = msg;
	}

	public void MyDialogSetMsg(CharSequence msg) {
		g_Msg = msg;
	}

	public void setPosiBtnMsg(String posiMsg) {
		posiBtnMsg = posiMsg;
	}

	public void setNegaBtnMsg(String negaMsg) {
		negaBtnMsg = negaMsg;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mydialog_profile);
		btn_confirm = (Button) findViewById(R.id.btn_confirm);
		btn_confirm.setOnClickListener(this);
		btn_cancel = (Button) findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(this);
		container = (ViewGroup) findViewById(R.id.rl_container);
		lineSeperator = findViewById(R.id.dialog_btn_line_seperator);
		if (buttonNums == ButtonConfirm) {
			btn_cancel.setVisibility(View.GONE);
			lineSeperator.setVisibility(View.GONE);
			btn_confirm.setText(R.string.i_kuown);
			btn_confirm
					.setBackgroundResource(R.drawable.common_res_alertdialog_full_btn_selector);
		} else if (buttonNums == ButtonCancle) {
			btn_confirm.setVisibility(View.GONE);
			lineSeperator.setVisibility(View.GONE);
			btn_cancel
					.setBackgroundResource(R.drawable.common_res_alertdialog_full_btn_selector);
		} else if (buttonNums == ButtonNone) {
			btn_confirm.setVisibility(View.GONE);
			btn_cancel
					.setBackgroundResource(R.drawable.common_res_base_alertdialog_full_btn_bg_norrmal);
		}
		if (view != null) {
			container.removeAllViews();
			android.widget.RelativeLayout.LayoutParams params = new android.widget.RelativeLayout.LayoutParams(
					android.widget.RelativeLayout.LayoutParams.FILL_PARENT,
					android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
			container.addView(view, params);
		}

		
		mBaseInfoName = (EditText) findViewById(R.id.reg_baseinfo_et_name);//reg_baseinfo_et_name
		mBaseInfoNote = (EditText) findViewById(R.id.reg_baseinfo_et_usersign);//reg_baseinfo_et_usersign
		mRgGender = (RadioGroup) findViewById(R.id.reg_baseinfo_rg_gender);//reg_baseinfo_rg_gender
		mRbMale = (RadioButton) findViewById(R.id.reg_baseinfo_rb_male);//reg_baseinfo_rb_male
		mRbFemale = (RadioButton) findViewById(R.id.reg_baseinfo_rb_female);//reg_baseinfo_rb_female
		mHtvConstellation = (HandyTextView) findViewById(R.id.reg_birthday_htv_constellation);
		mHtvAge = (HandyTextView) findViewById(R.id.reg_birthday_htv_age);
		mDpBirthday = (DatePicker) findViewById(R.id.reg_birthday_dp_birthday);//reg_birthday_dp_birthday
		
		mBaseInfoName.addTextChangedListener(this);
		mBaseInfoNote.addTextChangedListener(this);
		mRgGender.setOnCheckedChangeListener(this);
		
		initData();

	}
	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		mIsChange = true;
//		if (!mIsGenderAlert) {
//			mIsGenderAlert = true;
//			mBaseDialog = BaseDialog.getDialog(activity, "提示", "注册成功后性别将不可更改",
//					"确认", new DialogInterface.OnClickListener() {
//
//						@Override
//						public void onClick(DialogInterface dialog, int which) {
//							dialog.dismiss();
//						}
//					});
//			mBaseDialog.show();
//		}
		switch (checkedId) {
		case R.id.reg_baseinfo_rb_male:
			mRbMale.setChecked(true);
			gender = "1";//默认0未知，1男male，2女female
			break;

		case R.id.reg_baseinfo_rb_female:
			mRbFemale.setChecked(true);
			gender = "2";//默认0未知，1男，2女
			break;
		}
	}
	
	@Override
	public void afterTextChanged(Editable s) {

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		mIsChange = true;
	}
	
	public boolean validate() {
		if (isNull(mBaseInfoName)) {
			showCustomToast("请输入姓名");
			mBaseInfoName.requestFocus();
			return false;
		}else{
			name = mBaseInfoName.getText().toString().trim();
		}
		if (isNull(mBaseInfoNote)) {
			showCustomToast("请输入个性签名");
			mBaseInfoNote.requestFocus();
			return false;
		}else{
			usersign = mBaseInfoNote.getText().toString().trim();
		}
		if (mRgGender.getCheckedRadioButtonId() < 0) {
			showCustomToast("请选择性别");
			return false;
		}
		return true;
	}
	protected boolean isNull(EditText editText) {
		String text = editText.getText().toString().trim();
		if (text != null && text.length() > 0) {
			return false;
		}
		return true;
	}
	
	
	
	private void flushBirthday(Calendar calendar) {
		String constellation = TextUtils.getConstellation(
				calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH));
		mSelectDate = calendar.getTime();
		mHtvConstellation.setText(constellation);
		int age = TextUtils.getAge(calendar.get(Calendar.YEAR),
				calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH));
		mHtvAge.setText(age + "");
	}

	private void initData() {
		mSelectDate = DateUtils.getDate("19900101");

		Calendar mMinCalendar = Calendar.getInstance();
		Calendar mMaxCalendar = Calendar.getInstance();

		mMinCalendar.set(Calendar.YEAR, mMinCalendar.get(Calendar.YEAR)
				- MIN_AGE);
		mMinDate = mMinCalendar.getTime();
		mMaxCalendar.set(Calendar.YEAR, mMaxCalendar.get(Calendar.YEAR)
				- MAX_AGE);
		mMaxDate = mMaxCalendar.getTime();

		mCalendar = Calendar.getInstance();
		mCalendar.setTime(mSelectDate);
		flushBirthday(mCalendar);
		mDpBirthday.init(mCalendar.get(Calendar.YEAR),
				mCalendar.get(Calendar.MONTH),
				mCalendar.get(Calendar.DAY_OF_MONTH), this);
	}
	
	@Override
	public void onDateChanged(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		mIsChange = true;
		mCalendar = Calendar.getInstance();
		if(year==0)
			year = 1990;
		if(monthOfYear==0)
			monthOfYear = 1;
		if(dayOfMonth==0)
			dayOfMonth = 1;
		mCalendar.set(year, monthOfYear, dayOfMonth);
		if (mCalendar.getTime().after(mMinDate)
				|| mCalendar.getTime().before(mMaxDate)) {
			mCalendar.setTime(mSelectDate);
			mDpBirthday.init(mCalendar.get(Calendar.YEAR),
					mCalendar.get(Calendar.MONTH),
					mCalendar.get(Calendar.DAY_OF_MONTH), this);
		} else {
			
			birthdayfull = year +"-"+ monthOfYear +"-"+dayOfMonth;
			birthyear = year+"";
			birthmonth = monthOfYear+"";
			birthday = dayOfMonth+"";
//			mActivity.attributes.put("birthyear", year+"");
//			mActivity.attributes.put("birthmonth", monthOfYear+"");
//			mActivity.attributes.put("birthday", dayOfMonth+"");
//			birthday = year +"-"+ (monthOfYear+1) +"-"+dayOfMonth;
			flushBirthday(mCalendar);
		}
	}
	
	@Override
	protected void onStart() {
//		if (!visiable) {
//			theView.setVisibility(View.GONE);
//		}
//		if (g_Msg != null && !g_Msg.equals("")) {
//			theView.setText(g_Msg);
//		}
		if (name  != null && !name .equals(""))
			mBaseInfoName.setText(name);
		if (usersign  != null && !usersign .equals(""))
			mBaseInfoNote.setText(usersign);
		
		if(gender!=null && !gender.equals("")){////默认0未知，1男，2女
			if(gender.equals("1"))
				mRbMale.setChecked(true);
			else if(gender.equals("2"))
				mRbFemale.setChecked(true);
		}
		
		if(birthyear!=null && birthyear.length()!=0 && !birthyear.equalsIgnoreCase("null")
				&& birthmonth!=null && birthmonth.length()!=0 && !birthmonth.equalsIgnoreCase("null")
				&& birthday!=null && birthday.length()!=0 && !birthday.equalsIgnoreCase("null")){
			int birthyearInt = 1900;
			int birthmonthInt = 1;
			int birthdayInt = 1;
			try{
				birthyearInt = Integer.parseInt(birthyear);
				birthmonthInt = Integer.parseInt(birthmonth);
				birthdayInt = Integer.parseInt(birthday);
			}catch(Exception e){
				birthyearInt = 1900;
				birthmonthInt = 1;
				birthdayInt = 1;
			}
			mIsChange = true;
			mCalendar = Calendar.getInstance();
			mCalendar.set(birthyearInt, birthmonthInt, birthdayInt);
			if (mCalendar.getTime().after(mMinDate)
					|| mCalendar.getTime().before(mMaxDate)) {
				mCalendar.setTime(mSelectDate);
				mDpBirthday.init(mCalendar.get(Calendar.YEAR),
						mCalendar.get(Calendar.MONTH),
						mCalendar.get(Calendar.DAY_OF_MONTH), this);
			} else {
				flushBirthday(mCalendar);
			}
		}
		
//		if (title != null && !title.equals("")) {
//			tx_title.setText(title);
//		}
		if (!posiBtnMsg.equals("")) {
			btn_confirm.setText(posiBtnMsg);
		}
		if (!negaBtnMsg.equals("")) {
			btn_cancel.setText(negaBtnMsg);
		}
		super.onStart();
	}

	@Override
	public void onClick(View v) {
		if (listener != null || contentListener != null) {
			if (v.getId() == R.id.btn_confirm) {
				if(listener != null)
				listener.onPositiveClick(this, v);
			} else if (v.getId() == R.id.btn_cancel) {
				if(listener != null)
				listener.onNegativeClick(this, v);
			} else if (v.getId() == R.id.textViewDialog) {
				if(contentListener != null)
				contentListener.onClickContent(this, v, g_Msg);
			}
		}
//		if(v.getId() == R.id.tv_select_input){//下拉选择框
//            // 点击控件后显示popup窗口
//            initSelectPopup();
//            // 使用isShowing()检查popup窗口是否在显示状态
//            if (typeSelectPopup != null && !typeSelectPopup.isShowing()) {
//                typeSelectPopup.showAsDropDown(mSelectTv, 0, 10);
//            }
//		}
		else if (isShowing()) {
			dismiss();
		}
	}

	public void setMsgViewVisiable(boolean visiable) {
		this.visiable = visiable;
	}

	public interface MyDialogListener {
		public void onPositiveClick(Dialog dialog, View view);

		public void onNegativeClick(Dialog dialog, View view);
	}

	public interface MyDialogContentClickListener {
		public void onClickContent(Dialog dialog, View view,
				CharSequence content);
	}

	@Override
	public void show() {
		if (activity != null && !activity.isFinishing()) {
			super.show();
		}
	}

	public void setView(View view) {
		this.view = view;
	}
	

	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(this.activity).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(this.activity);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
}
